import request from "../../request"
import _ from 'lodash'

export async function uploadFile(uploadFile, config = {}) {
    const res = await request.upload("/public", "/system/uploadFile", { file: uploadFile, dir: 'work_ai' }, {
        onUploadProgress: (progressEvent_1) => {
            config.onUploadProgress && config.onUploadProgress({
                loaded: progressEvent_1.loaded,
                total: progressEvent_1.total,
                percent: (progressEvent_1.loaded / progressEvent_1.total).toFixed(2)
            })
        }
    })

    return ({
        name: uploadFile.name,
        size: uploadFile.size,
        ...res
    })
}

export async function uploadFiles(uploadFiles, config = {}) {
    let files = _.cloneDeep(uploadFiles)

    let totalLoaded = 0
    let totalSize = files.reduce((total, item) => total + item.size, 0)

    let responses = []

    while (files.length > 0) {
        // 取出前五个
        let uploadFiles = files.splice(0, 5)

        let uploadRequests = uploadFiles.map(async file => {
            let lastLoaded = 0

            const res = await uploadFile(
                file,
                {
                    onUploadProgress: (progressEvent) => {
                        let total = progressEvent.loaded - lastLoaded
                        lastLoaded = progressEvent.loaded
                        totalLoaded += total

                        config.onUploadProgress && config.onUploadProgress({
                            loaded: totalLoaded,
                            total: totalSize,
                            percent: (totalLoaded / totalSize).toFixed(2)
                        })
                    }
                }
            )

            return {
                name: file.name,
                size: file.size,
                ...res,
            }
        })
        
        responses = responses.concat(await Promise.all(uploadRequests))
    }

    return responses
}

export async function upload(file, config = {}) {
    if(Array.isArray(file)){
        return uploadFiles(file, config)
    }

    return uploadFile(file, config)
}